<?php
/**
 * 搜索管理
 */
namespace app\index\controller;

use app\common\controller\Homebase;
use app\common\model\News as news_model;
use app\common\model\Column as column_model;
use app\common\model\TagData;
use app\common\model\Search as search_model;
use util\Page;
use XS;

class Search extends Homebase
{
    public function initialize()
    {
        parent::initialize();
        $this->column_model = new column_model();
        $this->news_model   = new news_model();
        $this->tag_data     = new TagData();
        $this->search_model = new search_model();
    }

    public function index()
    {
        $q_str = input('get.q');
        $page  = input('get.page', 1, 'intval');
        $rows  = 10;   // 每页条数
        $q     = htmlentities(trim($q_str));
        $q     = remove_xss($q);
        $list  = [];

        $page_total = 0;
        $page_show  = '';
        if (isset($q) && $q != '') {
            $q          = get_zh_string($q, 38, '');
            $xs         = new XS('news');
            $search     = $xs->search;
            $count      = $search->count($q);
            $page_total = ceil($count/$rows);
            if ($page > $page_total) {
                $page = $page_total;
            }
            $begin = ($page-1)*$rows;
            $docs  = $search->setLimit($rows, $begin)->search($q);
            if (!empty($docs)) {
                foreach ($docs as $key=>$doc) {
                    $list[$key]['id']          = $doc->id;
                    $list[$key]['column_id']   = $doc->column_id;
                    $list[$key]['title']       = $search->highlight($doc->title);
                    $list[$key]['keywords']    = $search->highlight($doc->keywords);
                    $list[$key]['description'] = $search->highlight($doc->description);
                    $list[$key]['read_number'] = $doc->read_number;
                    $list[$key]['author']      = $doc->author;
                    $list[$key]['is_original'] = $doc->is_original;
                    $list[$key]['create_time'] = $doc->create_time;
                }
                // 获取分页内容
                $page_class = new Page($count, $rows, ['q'=>$q], Url('/search'));
                $page_show  = $page_class->render();
            }

            $this->search_model->saveSearchData($q);
        }

        $id_column = $this->column_model->getColumnIdKeyList();

        $this->assign('q', $q);
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign('page_total', $page_total);
        $this->assign('id_column', $id_column);
        $this->assign('page_show', $page_show);

        return $this->fetch();
    }

}
